//
//  GXHomeChangeNameController.m
//  YIChuSeller
//
//  Created by 田小椿 on 2018/12/3.
//  Copyright © 2018年 xiangshengjun. All rights reserved.
//

#import "GXHomeChangeNameController.h"
#define MAX_WORDS_LENGTH 20
@interface GXHomeChangeNameController ()
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;

@end

@implementation GXHomeChangeNameController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置昵称";
    self.view.backgroundColor = kGlobalbgColor;
    [self.nameTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
}
- (void)setUPNavigationRightItem
{
    UIButton * rightButton = [UIButton setButtonTitleNormal:@"保存" buttonTintColor:[UIColor whiteColor]];
    [rightButton addTarget:self action:@selector(clickSaveButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}
- (void)clickSaveButton:(UIButton *)saveBtn
{
    
}
- (void)textFieldDidChange{
    self.numberLabel.text = [NSString stringWithFormat:@"%lu/%d", (unsigned long)[self.nameTextField.text length],20];
    NSString *toBeString = self.nameTextField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [self.nameTextField markedTextRange];
    UITextPosition *position = [self.nameTextField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        
        if (toBeString.length > MAX_WORDS_LENGTH){
            
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_WORDS_LENGTH];
            if (rangeIndex.length == 1){
                
                self.nameTextField.text = [toBeString substringToIndex:MAX_WORDS_LENGTH];
            }
            else{
                
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_WORDS_LENGTH)];
                self.nameTextField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.nameTextField resignFirstResponder];
}

@end
